<?php
declare (strict_types=1);

namespace app\sysuser\controller\say;

use app\common\controller\SysBackend;
use app\common\enums\say\SayTeachSentenceStatusEnum;
use app\common\model\banxi\say\SayTeachSentence as SayTeachSentenceModel;
use app\common\service\ImportService;
use app\common\service\queue\QueueService;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class TeachSentence extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SayTeachSentenceModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->filter('trim')->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListPage($where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }


    /**
     * 分页Select查询
     * @return void
     * @throws DbException
     */
    public function listSelectPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", 'searchText']);
        if (!empty($param['searchText'])) {
            $param['query']['LIKE_sentenceEn'] = $param['searchText'];
        }
        $param['query']['EQ_status'] = SayTeachSentenceStatusEnum::E1;
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListSelectPage($where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->getInfo($where);
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $info['parentId'] = (string)$info['parentId'];
        $this->ok('操作成功', $info);
    }

    /**
     * 新增或修改
     * @return void
     */
    public function saveOrUpdate()
    {
        $param = $this->request->filter('trim')->param([
            'id' => null, 'parentId' => 0, 'gradeId' => '', 'sentenceEn' => '', 'sentenceZh' => '',
            'sentencePhonetic' => '', 'sentenceAudio' => '', 'name' => '', 'sentenceGroupEn' => '', 'sentenceGroupZh' => '',
            'sentenceImage' => '', 'splitSentenceList' => [], 'sentenceWordColorList' => [], 'intonationGroupList' => [],
            'coreVocabularyList' => [], 'expandVocabularyList' => [], 'question' => '', 'answerList' => '', 'status' => 1,
            'sortNum' => 1,'courseExperience'=>0
        ]);
        try {
            $validate = Validate::rule([
                'parentId' => ValidateRule::isRequire(null, '请设置上级ID'),
                'gradeId' => ValidateRule::isRequire(null, '请选择年级'),
                'sentenceGroupEn' => ValidateRule::isRequire(null, '请输入本组英文句型'),
                'sentenceGroupZh' => ValidateRule::isRequire(null, '请输入本组中文句型'),
                'sentenceEn' => ValidateRule::isRequire(null, '请输入英文句子'),
                'sentenceZh' => ValidateRule::isRequire(null, '请输入中文句子'),
                'sentencePhonetic' => ValidateRule::isRequire(null, '请输入句子音标'),
                'sentenceAudio' => ValidateRule::isRequire(null, '请输入句子音频'),
                'name' => ValidateRule::isRequire(null, '请输入句子功能'),
                'sentenceImage' => ValidateRule::isRequire(null, '请设置句型图片'),
                'splitSentenceList' => ValidateRule::isRequire(null, '请输入拆分句子'),
                'sentenceWordColorList' => ValidateRule::isRequire(null, '请输入拆分句子'),
                'intonationGroupList' => ValidateRule::isRequire(null, '请设置句子单词颜色'),
                'coreVocabularyList' => ValidateRule::isRequire(null, '请设置核心词汇'),
                // 'expandVocabularyList' => ValidateRule::isRequire(null, '请设置拓展词汇'),
                'question' => ValidateRule::isRequire(null, '请设置问题'),
                'answerList' => ValidateRule::isRequire(null, '请设置问题答案'),
                'status' => ValidateRule::IN([1, 2], '请设置正确的状态'),
                'sortNum' => ValidateRule::isRequire(null, '请设置排序数'),
                'courseExperience' => ValidateRule::isBool(null, '请设置是否是体验课')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->saveOrUpdate($param);
            $queueService = new QueueService();
            $queueService->addSayWordSplitJob($param['coreVocabularyList']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }


    public function del()
    {
        $param = $this->request->param(['ids' => []]);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->del($param['ids']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function import()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->fail(__('请选择导入的文件'));
        }

        $importService = new ImportService();
        $res = $importService->saySentenceImport($file);
        if (!$res) {
            $this->fail(__($importService->getError()));
        }
        $this->ok(__('导入成功'),  [], self::NOTIFICATION);
    }

    /**
     * 分页-学员开通课程查询
     * @return void
     * @throws DbException
     */
    public function listStudentOpenPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", "isPractice", "studentId"]);
        // die;
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListStudentOpenPage((bool)$param['isPractice'], $param['studentId'], $where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 分页-学员未开通课程查询
     * @return void
     * @throws DbException
     */
    public function listStudentPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", "studentId"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListStudentPage( $param['studentId'], $where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }


}
